package Service;

import java.util.Date;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;

import DAO.bookDAO;
import DAO.borrowDAO;
import DAO.userDAO;
import DAO.user_bookDAO;
import HibernateUtilsforBM.SFactoryGenerator;
import Model.borrow;
import Model.user;
import Model.user_book;

/**
 * 借书服务
 * @author MacBook
 *
 */
public class borrowService {
	//用户借书服务
	public boolean borrowBookService(String username,int bookid){
		Session session = SFactoryGenerator.getSession();
		Transaction tx = session.beginTransaction();
		boolean isSuccess = false;
		//获得书本的数量 不足时候不能借书
		int numbers = bookDAO.getBookNumber(session, bookid);
		if(numbers <= 0)
			return isSuccess;
		try {
			user u = userDAO.findByUsername(session, username);
			borrow b = borrowDAO.findRecord(session, u.getUserid(), bookid);
			if(u != null || b == null){
				//借书表更新记录，并且书本数量减一
				b = new borrow(u.getUserid(),bookid,new Date());
				borrowDAO.save(session, b);
				bookDAO.bookout(session, bookid);
				isSuccess = true;
			}
			tx.commit();
		} catch (Exception e) {
			// TODO: handle exception
			tx.rollback();
		}finally {
			session.close();
		}
		return isSuccess;
	}
	//用户查看手上的书
	public List<user_book> user_bookList(int userid){
		Session session = SFactoryGenerator.getSession();
		Transaction tx = session.beginTransaction();
		List<user_book> list = null;
		try {
			list = user_bookDAO.user_bookList(session, userid);
		} catch (Exception e) {
			// TODO: handle exception
			tx.rollback();
		}finally {
			session.close();
		}
		return list;
	}
	//还书服务
	public void returnBookService(int userid,int bookid){
		Session session = SFactoryGenerator.getSession();
		Transaction tx = session.beginTransaction();
		try {
			//删除借书记录并且numbers增加
			borrowDAO.removeRecord(session, userid, bookid);
			bookDAO.bookin(session, bookid);
			tx.commit();
		} catch (Exception e) {
			// TODO: handle exception
			tx.rollback();
		}finally {
			session.close();
		}
	}
}
